<template>
  <div class="product">
    <van-nav-bar
      title="商品"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-swipe :autoplay="3000">
      <van-swipe-item v-for="(image, index) in images" :key="index">
        <img class="swImg" v-lazy="image.img_url" />
      </van-swipe-item>
    </van-swipe>
    <div class="tips">
      <span>30天无理由退换</span>
      <span>48小时极速退款</span>
      <span>满88元免邮费</span>
    </div>
    <div class="info">
      <h4 class="">{{ goodsinfo.name }}</h4>
      <p>{{ goodsinfo.goods_brief }}</p>
      <p>￥{{ goodsinfo.retail_price }}</p>
    </div>
    <van-cell title="请选择规格数量" is-link class="cell" @click="goodsAndNum" />
    <hr />

    <div class="arg">
      <h3>商品参数</h3>
      <p class="item" v-for="(item, index) in attribute" :key="index">
        <span>{{ item.name }}</span>
        <span>{{ item.value }}</span>
      </p>
    </div>

    <div class="desc" v-html="goodsinfo.goods_desc"></div>

    <!-- 商品购买栏 -->
    <van-goods-action>
      <van-goods-action-icon to="/buycart" icon="cart-o" text="购物车" :info="$store.state.cartTotal.goodsCount == 0?'':$store.state.cartTotal.goodsCount" />
      <van-goods-action-icon icon="star-o" text="已收藏" />
      <van-goods-action-button
        type="warning"
        text="加入购物车"
        @click="chooseGoods"
      />
      <van-goods-action-button type="danger" text="立即购买" />
    </van-goods-action>

    <!-- sku -->
    <van-sku
      v-model="show"
      :sku="sku"
      :goods="goods"
      @buy-clicked="onBuyClicked"
      @add-cart="onAddCartClicked"
    />
  </div>
</template>

<script>
import axios from "axios";
let sku = {
  // 所有sku规格类目与其值的从属关系，比如商品有颜色和尺码两大类规格，颜色下面又有红色和蓝色两个规格值。
  // 可以理解为一个商品可以有多个规格类目，一个规格类目下可以有多个规格值。
  tree: [
    {
      k: "颜色", // skuKeyName：规格类目名称
      k_s: "s1", // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
      v: [
        {
          id: "1", // skuValueId：规格值 id
          name: "红色", // skuValueName：规格值名称
          imgUrl: "https://img.yzcdn.cn/1.jpg", // 规格类目图片，只有第一个规格类目可以定义图片
          previewImgUrl: "https://img.yzcdn.cn/1p.jpg", // 用于预览显示的规格类目图片
        },
        {
          id: "1",
          name: "蓝色",
          imgUrl: "https://img.yzcdn.cn/2.jpg",
          previewImgUrl: "https://img.yzcdn.cn/2p.jpg",
        },
      ],
      largeImageMode: true, //  是否展示大图模式
    },
  ],
  // 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
  list: [
    {
      id: 2259, // skuId
      's-1': '2', // 规格类目 k_s 为 s1 的对应规格值 id
      's-2': '3', // 规格类目 k_s 为 s2 的对应规格值 id
      price: 100, // 价格（单位分）
      stock_num: 110, // 当前 sku 组合对应的库存
    },
    {
      id: 2259, // skuId
      's-1': '1', // 规格类目 k_s 为 s1 的对应规格值 id
      's-2': '4', // 规格类目 k_s 为 s2 的对应规格值 id
      price: 130, // 价格（单位分）
      stock_num: 130, // 当前 sku 组合对应的库存
    },
  ],
  price: "1.00", // 默认价格（单位元）
  stock_num: 227, // 商品总库存

};
export default {
  props: ["id"],
  data() {
    return {
      data: {},
      goodsinfo: {},
      attribute: {},
      show: false,
      sku: sku,
      goods: {
        // 默认商品 sku 缩略图
        picture: "https://img.yzcdn.cn/1.jpg",
      },
      messageConfig: {
        // 数据结构见下方文档
      },
    };
  },
  computed: {
    images: function () {
      return this.data.gallery;
    },
  },
  methods: {
    goodsAndNum(){
      this.show = true
    },
    onClickLeft: function () {
      this.$router.go(-1);
    },
    
    onBuyClicked() {},
    async onAddCartClicked(skudata) {
      this.show = false;
      console.log(skudata)
      let chooseContent = skudata.selectedSkuComb['s-1']+'_'+skudata.selectedSkuComb['s-2']
      let res =  this.data.productList.filter(item =>{
        if(item.goods_specification_ids == chooseContent){
          return true
        }else{
          return false
        }
      })
      console.log(res)
      //将数据发给服务器
      let cartRes = await axios.post(this.$root.api.CartAdd,{goodsId:res[0].goods_id, number: skudata.selectedNum, productId: res[0].id  })
      console.log(cartRes)

      this.$store.commit('setCartTotal',cartRes.data.data.cartTotal)
      this.$store.commit('setCartList',cartRes.data.data.cartList)

    },
    chooseGoods() {
      this.show = true;
    },
  },
  async created() {
    this.$store.dispatch('AjaxCart')
    let res = await axios(this.$root.api.GoodsDetail, {
      params: { id: this.id },
    });
    this.data = res.data.data;
    this.goodsinfo = this.data.info;
    this.attribute = this.data.attribute;
    this.goods.picture = this.data.info.primary_pic_url
    this.sku.price = this.data.info.retail_price
    this.sku.stock_num = this.data.info.goods_number
    console.log(this.data);

    //产品规格
    let tree = []
    this.data.specificationList.forEach((item) =>{
        let arr = []
        item.valueList.forEach(item1 =>{
          arr.push({
            id: item1.id,
            name: item1.value,
            imgUrl: item.pic_url
          })
        })

        tree.push({
          k: item.name,
          k_s: "s-"+item.specification_id,
          v: arr
        })
    })
    this.sku.tree = tree


    
  
  },
};
</script>

<style lang="less" scoped>
.product {
  .swImg {
    width: 100%;
  }

  .tips {
    font-size: 10px;
    color: #ccc;
    display: flex;
    justify-content: space-around;
    height: 20px;
    line-height: 20px;
    background-color: #eee;

    span {
      position: relative;
    }

    span::before {
      content: "";
      position: absolute;
      width: 4px;
      height: 4px;
      border: 1px solid red;
      border-radius: 2px;
      top: 7px;
      left: -10px;
    }
  }

  .info {
    margin-top: 10px;
    h4 {
      font-weight: 500;
    }
    :nth-child(2) {
      font-size: 12px;
      color: #ccc;
      padding: 8px 0;
    }
    :nth-child(3) {
      font-size: 14px;
      color: lightcoral;
    }
  }

  .cell {
    text-align: left;
  }

  .arg {
    padding: 0 10px;
    h3 {
      padding: 10px 0;
    }
    .item {
      padding: 0 5px;
      justify-content: space-between;
      display: flex;
      font-size: 12px;
      text-align: left;
      background-color: #eee;
      height: 26px;
      line-height: 26px;
      color: #ccc;
      :nth-child(1) {
        width: 20%;
        border-right: 1px solid #ccc;
      }
      :nth-child(2) {
        width: 70%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }

  /deep/ .desc {
    width: 100%;
    p {
      margin: 0;
      padding: 0;
      img {
        display: flex;
        width: 100%;
      }
    }
  }
}
</style>